function u_diff=threshold_function_ep(theta)


%%%%% Estimates the threshold value of risk-aversion at which the expected utility
%%%%% of the two lotteries would be equal

%%% The necessary variables are the money at stake in each option of each
%%% lottery (a1, b1, ..., a2, b2, ...) and the corresponding probabilites
%%% of winning each option in each lottery (p_a1, p_b1, ...)

    global a1 b1 p_a1 a2 b2 p_a2
    

    %%% Abedellaoui et al 2007 one parameter expo-power function.
    %%% ep_parameter cannot equal 1 like in CRRA. Furthermore, prizes
    %%% (x) have to be normalized to lie between 0 and 1 (divide by top
    %%% value, see Abdellaoui et al., 2007, p. 19. Here the top value
    %%% is 128)
        
    a1_use=a1/128;
    b1_use=b1/128;
    a2_use=a2/128;
    b2_use=b2/128;

    %%% The parameter to be estimated to equalize the two equations is omega
    w=theta;

    %%% The assumed utility function is ep

    %%% The two lotteries are 1 and 2 where 1 is the less risky one
    
    if w~=1
        %%% the last term is added for numerical purposes (see Abdellaoui
        %%% et al., 2007, p. 8) 
        %%% utility of option a in the less risky lottery 1 (referred to  as X in the
        %%% paper)
        U_1_a=-exp(-((a1_use).^(1-w))./(1-w)+1./(1-w));
        %%% utility of option b in the less risky lottery 1 (referred to  as X in the
        %%% paper)
        U_1_b=-exp(-((b1_use).^(1-w))./(1-w)+1./(1-w));
    else
        %%% utility of option a in the less risky lottery 1 (referred to  as X in the
        %%% paper)
        U_1_a=-1./(a1_use);
        %%% utility of option b in the less risky lottery 1 (referred to  as X in the
        %%% paper)
        U_1_b=-1./(b1_use);
    end
    
    %%% Expected Utility of lottery 1
    U_1_E=p_a1.*U_1_a+(1-p_a1).*U_1_b;

    if w~=1
        %%% utility of option a in the riskier lottery 2 (referred to as Y in the
        %%% paper)
        U_2_a=-exp(-((a2_use).^(1-w))./(1-w)+1./(1-w));
        %%% utility of option b in the riskier lottery 2 (referred to as Y in the
        %%% paper)
        U_2_b=-exp(-((b2_use).^(1-w))./(1-w)+1./(1-w));
    else
        %%% utility of option a in the riskier lottery 2 (referred to as Y in the
        %%% paper)
        U_2_a=-1./(a2_use);
        %%% utility of option b in the riskier lottery 2 (referred to as Y in the
        %%% paper)
        U_2_b=-1./(b2_use);
    end

    %%% Expected Utility of lottery 2
    U_2_E=p_a2.*U_2_a+(1-p_a2).*U_2_b;

    u_diff=U_2_E-U_1_E;

end